<template>
  <div class="shopcart">
    <div class="left">
      <div class="icon">
        <div class="inner">
        </div>
      </div>
      <div class="money">
        总计：￥{{totalmoney}}
      </div>
    </div>
    <div @click="commitOrder" class="right" :class="{'highlight':totalcount>0}">
      {{paytext}}
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import {Toast, Dialog} from 'vant';

  export default {
    data() {
      return {
        show: false
      };
    },
    props: {
      selectFoods: {
        type: Array,
        default() {
          return [];
        }
      },
      user: {}
    },
    computed: {
      totalmoney() {
        let total = 0;
        this.selectFoods.forEach((food) => {
          total += food.count * food.price;
        });
        return total;
      },
      totalcount() {
        let total = 0;
        this.selectFoods.forEach((food) => {
          total += food.count;
        });
        return total;
      },
      paytext() {
        if (this.totalcount === 0) {
          return '请选择商品';
        } else {
          return '点击确认';
        }
      }
    },
    methods: {
      async commitOrder() {
        if (this.totalcount === 0) {
          Toast.fail('您的购物车中没有商品！');
        } else {
          Dialog.confirm({
            title: '订单确认',
            message: this.getSelectFoodSimpleDesc()
          }).then(async () => {
            // 发送请求
            this.show = true;
            var foodIds = '';
            this.selectFoods.forEach((food) => {
              foodIds += food.foodId + '-';
            });
            const data = {
              userId: this.user.userId,
              selectFoods: foodIds,
              amount: this.totalmoney
            };
            const response = await this.$store.order.commit(data);
            if (response.code === '200') {
              window.alert('请扫描二维码付款，并填写备注信息,需支付：' + this.totalmoney);
            } else {
              window.alert(response.message);
            }
          }).catch(() => {
          });
        }
      },
      getSelectFoodSimpleDesc() {
        let fullname = '商品：';
        this.selectFoods.forEach((food, index) => {
          if (index === this.selectFoods.length - 1) {
            fullname += food.foodName;
          } else {
            fullname += food.foodName + '-';
          }
        });
        fullname += '    总价：' + this.totalmoney;
        return fullname;
      }
    }
  };
</script>

<style lang="stylus" type="text/stylus" rel="stylesheet/stylus">
  .shopcart
    position relative
    display flex
    height 46px
    .left
      flex 1
      background #141d27
      .money
        color #fff
        line-height 46px
        padding-left 18px
    .right
      flex 0 0 105px
      background rgb(43, 51, 59);
      color #fff
      line-height 46px
      text-align center
      &.highlight
        background: #00b43c
        color #fff
</style>
